package com.shj.service.impl;

import com.shj.dao.SysAreaMapper;
import com.shj.entity.SysArea;
import com.shj.service.SysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author songhuajian
 * @Description: TODO
 * @date 2020/5/10 17:54
 **/
@Service("sysAreaService")
public class SysAreaServiceImpl implements SysAreaService {
    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Override
    public List<SysArea> findAll() {
        return sysAreaMapper.findAll();
    }

    @Override
    public List<SysArea> findByGrade(int grade1, int grade2) {
        return sysAreaMapper.findByGrade(grade1, grade2);
    }

    @Override
    public List<SysArea> findChildArea(String areaCode, int grade) {
        return sysAreaMapper.findChildArea(areaCode, grade);
    }

    @Override
    public SysArea findByCode(String areaCode) {
        return sysAreaMapper.selectByPrimaryKey(areaCode);
    }

    @Override
    public int add(SysArea sysArea) {
        // 获取父节点的对象
        String pCode = sysArea.getAreaCode();
        SysArea pArea = sysAreaMapper.selectByPrimaryKey(pCode);
        // 生成行政区域编号
        String areaCode = createAreaId(pArea);
        sysArea.setAreaCode(areaCode);
        sysArea.setGrade(pArea.getGrade() + 1);
        return sysAreaMapper.insert(sysArea);
    }

    @Override
    public int edit(SysArea sysArea) {
        return sysAreaMapper.update(sysArea);
    }

    @Override
    public int delete(String areaCode) {
        return sysAreaMapper.delete(areaCode);
    }

    /**
     * @Description 自动生成行政区域编号
     * @author songhuajian
     * @date 2020/5/11 15:48
     */
    @Override
    public String createAreaId(SysArea sysArea) {
        int number=1;
        String maxCode = sysAreaMapper.maxCode(sysArea);
        if(maxCode != null){
            int beginIndex = maxCode.length()-2;
            String no = maxCode.substring(beginIndex);
            number = Integer.parseInt(no);
            ++number;
            //使用0补足位数
            no = String.format("%02d", number);
            maxCode = sysArea.getAreaCode() + no;
        }else{
            String no = String.format("%02d", number);
            maxCode = sysArea.getAreaCode() + no;
        }
        return maxCode;
    }
}
